package com.hgkj.cloud.base.util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class DataUtil {
	/**
	 * 睡眠报告曲线图标准差计算 
	 * 算法公式 s^2=[(x1-x)^2 +(x2-x)^2 +.(xn-x)^2]/(n-1) 
	 * x 表示平均值，x1,x2...xn表示当前值
	 */
	public static List<List<String>> bzcDataCount(String valStr, int beginIndex) {
		List<List<String>> reList = new ArrayList<>();
		String[] valStrs = valStr.split(",");
		List<String> up_points = new ArrayList<>();
		List<String> down_points = new ArrayList<>();
		for (int i = beginIndex; i < valStrs.length; i++) {
			double childTotal = 0;
			for (int j = 0; j < i + 1; j++) {
				childTotal += Double.valueOf(valStrs[j]);
			}
			// x
			double childAvg = childTotal / (i + 1);
			// [(x1-x)^2 +(x2-x)^2 +.(xn-x)^2]
			double totalTmp = 0;
			for (int j = 0; j < i + 1; j++) {
				// (x1-x)^2
				totalTmp += Math.pow(Math.abs(Double.valueOf(valStrs[j]) - childAvg), 2);
			}
			// 最后计算结果
			double upTotal = childAvg + Math.sqrt((totalTmp / i)) * 1.96;
			double downTotal = childAvg - Math.sqrt((totalTmp / i)) * 1.96;
			if (i == 1) {
				up_points.add(0, new BigDecimal(upTotal).setScale(2, BigDecimal.ROUND_DOWN).toString());
				down_points.add(0, new BigDecimal(downTotal).setScale(2, BigDecimal.ROUND_DOWN).toString());
				up_points.add(i, new BigDecimal(upTotal).setScale(2, BigDecimal.ROUND_DOWN).toString());
				down_points.add(i, new BigDecimal(downTotal).setScale(2, BigDecimal.ROUND_DOWN).toString());
			} else {
				up_points.add(new BigDecimal(upTotal).setScale(2, BigDecimal.ROUND_DOWN).toString());
				down_points.add(new BigDecimal(downTotal).setScale(2, BigDecimal.ROUND_DOWN).toString());
			}
		}
		reList.add(up_points);
		reList.add(down_points);
		return reList;
	}

	/**
	 * 计算百分比（四舍五入，保留小数）
	 *
	 * @param total 总数
	 * @param num   占比数
	 * @param bit   保留小数位
	 * @return double
	 */
	public static double getPercent(long total, long num, int bit) {
		total = total == 0 ? 1 : total;
		BigDecimal bg = new BigDecimal((double) num * 100 / total);
		double p = bg.setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
		return (p);
	}

	public static double getPercent(long total, long num) {
		return getPercent(total, num, 2);
	}

//	public static void main(String[] args) {
//		String valStr = "70,80,75,85,75,65,55,58";
//		int beginIndex = 1;
//		bzcDataCount(valStr, beginIndex);
//	}
}
